import { defineStore } from 'pinia';
import { ref, computed, shallowRef } from 'vue';
import musicService from '../services/musicService';
import { ElMessage } from 'element-plus';

export const useMusicStore = defineStore('music', () => {
  const audio = shallowRef(new Audio());
  const playlist = ref([]);
  const currentSongIndex = ref(-1);
  const isPlaying = ref(false);
  const currentTime = ref(0);
  const duration = ref(0);

  const currentSong = computed(() => playlist.value[currentSongIndex.value] || null);

  const loadPlaylist = async (playlistId) => {
    try {
      const data = await musicService.getPlaylistDetail(playlistId);
      // 存储歌曲的 fee 状态，用于UI显示
      playlist.value = data.tracks.map(track => ({
        id: track.id,
        name: track.name,
        artist: track.ar.map(a => a.name).join(' / '),
        albumArt: track.al.picUrl,
        url: null,
        fee: track.fee, // 存储fee状态 (1 表示VIP)
      }));
      ElMessage.success(`歌单 "${data.name}" 加载成功！`);
      if (playlist.value.length > 0) {
        playSong(0);
      }
    } catch (error) {
      ElMessage.error(error.message);
    }
  };

  const playSong = async (index) => {
    if (index < 0 || index >= playlist.value.length) return;
    currentSongIndex.value = index;
    isPlaying.value = false;

    // 处理 service 返回的新对象格式
    const songInfo = await musicService.getSongUrl(currentSong.value.id);

    if (!songInfo || !songInfo.url) {
      ElMessage.error(`歌曲 "${currentSong.value.name}" 无法播放，已自动跳过。`);
      nextSong();
      return;
    }

    // 如果是试听版，给出提示
    if (songInfo.isTrial) {
      ElMessage.warning({
        message: '该歌曲为会员专享，当前播放为试听片段。',
        duration: 5000, // 提示显示5秒
      });
    }

    // 更新URL并播放
    playlist.value[index].url = songInfo.url;
    audio.value.src = songInfo.url;
    audio.value.play().catch(e => console.error("播放失败:", e));
  };
  
  const playSongFromSearch = (song) => {
    const formattedSong = {
      id: song.id,
      name: song.name,
      artist: song.ar.map(a => a.name).join(' / '),
      albumArt: song.al.picUrl,
      url: null,
      fee: song.fee, // 从搜索结果中也记录fee状态
    };
    playlist.value.unshift(formattedSong);
    playSong(0);
  };
  
  const togglePlayPause = () => {
    if (!currentSong.value) return;
    if (isPlaying.value) {
      audio.value.pause();
    } else {
      audio.value.play().catch(e => console.error("播放失败:", e));
    }
  };

  const nextSong = () => {
    if (playlist.value.length === 0) return;
    let newIndex = currentSongIndex.value + 1;
    if (newIndex >= playlist.value.length) newIndex = 0;
    playSong(newIndex);
  };

  const prevSong = () => {
    if (playlist.value.length === 0) return;
    let newIndex = currentSongIndex.value - 1;
    if (newIndex < 0) newIndex = playlist.value.length - 1;
    playSong(newIndex);
  };

  const updateCurrentTime = (time) => {
    audio.value.currentTime = time;
  };

  audio.value.ontimeupdate = () => { currentTime.value = audio.value.currentTime; };
  audio.value.onloadedmetadata = () => { duration.value = audio.value.duration; };
  audio.value.onended = () => { nextSong(); };
  audio.value.onplay = () => { isPlaying.value = true; };
  audio.value.onpause = () => { isPlaying.value = false; };

  return {
    playlist,
    currentSongIndex,
    isPlaying,
    currentTime,
    duration,
    currentSong,
    loadPlaylist,
    playSong,
    playSongFromSearch,
    togglePlayPause,
    nextSong,
    prevSong,
    updateCurrentTime,
  };
});